<?php

namespace Icsoc\AgentBundle\Controller;

use Icsoc\CoreBundle\Controller\BaseController;
use Icsoc\CoreBundle\Export\DataType\ArrayType;
use Icsoc\SecurityBundle\Entity\WinAgqu;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\File;
use Icsoc\ExportLib\Col;

/**
 * 坐席管理
 * Class AgentController
 *
 * @package Icsoc\AgentBundle\Controller
 */
class AgentController extends BaseController
{
    const BATCH_DIR = '/var/agent/batch'; //存放批量导入的文件地址

    public $agStatus = array(
        1 => '在职',
        2 => '离职',
        3 => '冻结',
    );

    /**
     * 坐席列表；
     *
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $filter = $request->get('filter', '');

        $em = $this->getDoctrine()->getManager();
        $vccId = $this->getVccId();
        $vccCode = $this->getVccCode();
        $roleGrade = $this->getRoleGrade();
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        $flag = $user->getFlag();
        $isAdmin = false;
        if ($flag == 'ccadmin' || $flag == 'ccod') {
            $isAdmin = true;
        }
        //技能组
        $queues = $em->getRepository('IcsocSecurityBundle:WinQueue')
            ->getQuesName("q.vccId = :vccId AND q.isDel = 0", array('vccId' => $vccId));
        //角色
        $roleWhere = $roleGrade < 3 ? "AND r.roleGrade > :roleGrade" : "AND r.roleGrade = :roleGrade";
        $roles = $em->getRepository("IcsocSecurityBundle:CcRoles")
            ->getRolesName("r.vccId = :vccId $roleWhere", array('vccId' => $vccId, 'roleGrade' => $roleGrade));
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->isEnableGroup($vccId);
        //数据权限
        $dataRole = $this->container->getParameter('select_data_role');
        $dataRole = $this->container->get("icsoc_core.common.class")->getUserTypes($dataRole, $roleGrade);
        //坐席类型
        $agType = $this->container->get("icsoc_core.common.class")->getFrontAgentRole($roleGrade);
        /*获取所有业务组*/
        $groups = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
        $phone = $this->get("icsoc_data.model.phone")->getList(array('vcc_code' => $vccCode));
        $actionList = $this->getActionList();
        $actions = explode(',', $actionList);
        $allowAction['isDel'] = ($actionList == 'all' || in_array('icsoc_agent_del', $actions)) ? true : false;
        $allowAction['isAdd'] = ($actionList == 'all' || in_array('icsoc_agent_add', $actions)) ? true : false;
        $allowAction['isEdit'] = ($actionList == 'all' || in_array('icsoc_agent_edit', $actions)) ? true : false;
        $allowAction['isLogin'] = ($actionList == 'all' || in_array('icsoc_agent_login', $actions)) ? true : false;
        $allowAction['loginEnter'] = ($actionList == 'all' || in_array('icsoc_agent_login_enter', $actions)) ? true : false;
        $allowAction['loginEdit'] = ($actionList == 'all' || in_array('icsoc_agent_login_edit', $actions)) ? true : false;

        return $this->render('IcsocAgentBundle:Agent:index.html.twig', array(
            'queValues' => $queues,
            'roleValues' => $roles,
            'dataRole' => $dataRole,
            'agType' => $agType,
            'groups' => $groups,
            'allowAction' => $allowAction,
            'isEnableGroup' => $isEnableGroup,
            'phones' => isset($phone['data']) ? $phone['data'] : array(),
            'rows' => $rows,
            'page' => $page,
            'filter' => json_decode($filter, true),
            'isAdmin' => $isAdmin,
        ));
    }

    /**
     * 获取坐席列表
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function listAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $vccId = $this->getUser()->getVccId();
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $filter = $request->get('filter', '');
        $isLogin = $request->get('isLogin', 1);
        $loginEnter = $request->get('loginEnter', 1);
        $loginEdit = $request->get('loginEdit', 1);
        $agentRole = $this->container->getParameter("front_agent_type"); //坐席角色
        $selectDataRole = $this->container->getParameter("select_data_role"); //坐席角色
        $info = array(
            'pagination' => array('rows' => $rows, 'page' => $page),
            'filter' => !empty($filter) ? json_decode($filter, true) : array(),
            'sort' => array('order' => $sord, 'field' => $sidx),
        );
        /** @var \Icsoc\SecurityBundle\Entity\CcCcods $ccCcod 取得该企业开通的坐席类型 */
        $ccCcod = $em->getRepository("IcsocSecurityBundle:CcCcods")->find($vccId);
        $agentType = $ccCcod->getAgentType();
        /* 取得所有角色列表 */
        //$roles = $em->getRepository("IcsocSecurityBundle:CcRoles")
        //   ->getRolesName("r.vccId = :vccId", array('vccId'=>$vccId));
        /*获取所有业务组*/
        $groups = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
        //获取所有技能组
        $queues = $em->getRepository('IcsocSecurityBundle:WinQueue')
            ->getQuesName("q.vccId = :vccId AND q.isDel = 0", array('vccId' => $vccId));
        $condtions = $this->get("icsoc_core.common.class")->getUserTypeCondition();
        if (isset($condtions['ag_id']) && !empty($condtions['ag_id'])) {
            $info['filter']['id'] = implode(',', $condtions['ag_id']);
        }
        if (isset($condtions['user_role']) && !empty($condtions['user_role'])) {
            $info['filter']['user_role'] = implode(',', $condtions['user_role']);
        }
        //html标签处理
        $info['filter']['keyword'] = empty($info['filter']['keyword']) ? '' : htmlentities($info['filter']['keyword']);
        $data = array();
        $vccCode = $this->getUser()->getVccCode();
        $list = $this->get('icsoc_data.model.agent')
            ->listAgent(array('vcc_code' => $vccCode, 'info' => json_encode($info)));
        if (isset($list['data']) && !empty($list['data'])) {
            foreach ($list['data'] as $k => $v) {
                $v['id'] = $v['ag_id'];
                if ($v['ag_role'] != -1) {
                    $v['is_login'] = $v['ag_type'] == 1 ? 0 : 1;
                    $quitStr = $v['pho_num'];
                    if ($isLogin == 1) {
                        $quitStr .= "【<a href='javascript:void(0);' title='".$this->trans('Exit static seat')."' onclick='fn_logout(\"".$v['ag_num']."\")'>";
                        $quitStr .= $this->trans('Logout')."</a>】";
                    }
                    if ($isLogin == 1 || $loginEdit == 1) {
                        $quitStr .= "【<a href='javascript:void(0)'; onclick='fn_edit(\"".$v['ag_num']."\")' title='修改静态坐席'>修改</a>】";
                    }
                    if ($agentType == 1) {
                        //动态坐席
                        $agentStr = $this->trans('Dynamic seat');
                        if ($isLogin == 1 || $loginEnter == 1) {
                            $agentStr .= "【<a title='".$this->trans('Login as static agents');
                            $agentStr .= "' onclick='fn_login(\"".$v['ag_num']."\")'>".$this->trans('Login')."</a>】";
                        }
                    } else {
                        //静态坐席
                        $agentStr = "<span style='color:red'>".$this->trans('No landing');
                        if ($isLogin == 1) {
                            $agentStr .= "</span>【<a href='javascript:void(0);' title='";
                            $agentStr .= $this->trans('Login as static agents')."' ";
                            $agentStr .= "onclick='fn_login(\"".$v['ag_num']."\")'>".$this->trans('Login')."</a>】";
                        }
                    }
                    $v['ag_type'] = $v['ag_type'] == 1 ? $agentStr : $quitStr;
                } else {
                    $v['is_login'] = 0;
                    $v['ag_type'] = "";
                }
                $v['group_name'] = isset($groups[$v['group_id']]) ? $groups[$v['group_id']] : '';
                $v['ag_role'] = isset($agentRole[$v['ag_role']]) ? $agentRole[$v['ag_role']] : '';
                $v['user_type'] = isset($selectDataRole[$v['user_type']]) ? $selectDataRole[$v['user_type']] : '';
                $v['crm_datarole'] = isset($selectDataRole[$v['crm_datarole']]) ?
                    $selectDataRole[$v['crm_datarole']] : '';
                $v['ag_status'] = isset($this->agStatus[$v['ag_status']]) ? $this->agStatus[$v['ag_status']] : '';
                $queIds = $em->getRepository('IcsocSecurityBundle:WinAgqu')
                    ->getQueId($v['ag_id']);
                $userQueues = '';
                $ellipsis = '';
                foreach ($queIds as $key => $value) {
                    if ($key > 1) {
                        $userQueues .= isset($queues[$value['queId']]) ? $queues[$value['queId']].',' : '';
                    } else {
                        $ellipsis .= isset($queues[$value['queId']]) ? $queues[$value['queId']].',' : '';
                        $userQueues .= isset($queues[$value['queId']]) ? $queues[$value['queId']].',' : '';
                    }
                }
                $v['queues'] = !empty($ellipsis) ? substr($ellipsis, 0, -1) : $this->trans('Unallocated');
                if (count($queIds) > 2) {
                    $v['queues'] .= '...';
                }
                $v['allqueues'] = !empty($userQueues) ? substr($userQueues, 0, -1) : $this->trans('Unallocated');
                $list['data'][$k] = $v;
            }
            $data['rows'] = $list['data'];
        }
        $data['page'] = $list['page'];
        $data['total'] = isset($list['totalPage']) ? $list['totalPage'] : 0;
        $data['records'] = isset($list['total']) ? $list['total'] : 0;

        return new JsonResponse($data);
    }

    /**
     * 添加坐席
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addAction(Request $request)
    {
        $defaultData['ag_password']['first'] = '123456';
        $agentForm = $this->createForm('agent_info_form', $defaultData);
        $user = $this->getUser();
        $roleGrade = $user->getRoleGrade();
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->isEnableGroup($user->getVccId());
        if ($request->getMethod() == 'POST') {
            $arr = $request->get('agent_info_form');
            $userType = isset($arr['user_type']) ? $arr['user_type'] : '';
            if ($userType == 3) {
                $arr['user_queues'] = isset($arr['user_groups']) ? $arr['user_groups'] : array();
            }
            $arr['vcc_code'] = $user->getVccCode();
            $arr['ag_password'] = $arr['ag_password']['first'] == $arr['ag_password']['second'] ?
                $arr['ag_password']['first'] : "123456";
            $encoder = $this->get('security.encoder_factory')->getEncoder($user);
            $arr['ag_password'] = $encoder->encodePassword($arr['ag_password'], $user->getSalt());
            //html标签处理
            $arr['ag_name'] = htmlentities($arr['ag_name']);
            $arr['ag_nickname'] = htmlentities($arr['ag_nickname']);
            $msg = $this->get('icsoc_data.model.agent')->addAgent($arr);
            if (isset($msg['code']) && ($msg['code'] == 200)) {
                $type = "success";
                $message = $this->trans('Add seats success');
            } else {
                $type = "danger";
                $message = $this->trans('Add seats failure').' '.isset($msg['message']) ? $msg['message'] : '';
            }
            $data = array(
                'data' => array(
                    'msg_detail' => $message,
                    'type' => $type,
                    'link' => array(
                        array('text' => $this->trans('Continue to add'), 'href' => $this->generateUrl('icsoc_agent_add')),
                        array('text' => $this->trans('Seating list'), 'href' => $this->generateUrl('icsoc_agent_index')),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        return $this->render('IcsocAgentBundle:Agent:agentInfo.html.twig', array(
            'form' => $agentForm->createView(),
            'agentId' => '',
            'vccId' => $user->getVccId(),
            'isEnableGroup' => $isEnableGroup,
            'roleGrade' => $roleGrade,
            'page' => 1,  //添加的时候 默认显示 第一页
            'rows' => 10,  //添加的时候 默认显示 10条
            'filter' => array(), //添加的时候 默认没有搜索条件
        ));
    }

    /**
     * 删除坐席
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function delAction(Request $request)
    {
        $id = $request->get('id', 0);
        $ids = explode(",", $id);
        $arr['vcc_code'] = $this->getUser()->getVccCode();
        //删除
        $arr['ag_id'] = $ids;
        $agNames = $this->container->get("doctrine.dbal.default_connection")->fetchAll(
            "SELECT id,ag_num FROM win_agent WHERE id IN ($id)"
        );
        $msg = $this->get('icsoc_data.model.agent')->deleteAgent($arr);
        $agents = array();
        foreach ($agNames as $value) {
            $agents[$value['id']] = $value['ag_num'];
        }
        if (isset($msg['code']) && $msg['code'] == 500) {
            $success = $error = array();
            foreach ($msg['data'] as $value) {
                if (isset($value['code']) && ($value['code'] == 200)) {
                    $success[] = isset($agents[$value['ag_id']]) ? $agents[$value['ag_id']] : '';
                } else {
                    $message = isset($agents[$value['ag_id']]) ? $agents[$value['ag_id']] : '';
                    $message .= $value['message'];
                    $error[] = $message;
                }
            }
            if (empty($error)) {
                $message = $this->trans('Delete success');
            } else {
                $message = $this->trans('Delete fail').'['.implode(',', $error)."] <br/>";
            }
            //$message = $this->trans('Delete fail').'['.implode(',', $error)."] <br/>";
            //$message .= $this->trans('Delete success').'['.implode(',', $success).'] <br/>';
            $res = array('error' => 0, 'message' => $message);
        } else {
            $res = array('error' => 1, 'message' => $msg['message']);
        }

        return new JsonResponse($res);
    }

    /**
     * 修改坐席
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editAction(Request $request)
    {
        $id = (int) $request->get('id', 0);
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $filter = $request->get('filter', '');

        $user = $this->getUser();
        $roleGrade = $user->getRoleGrade();
        $vccId = $user->getVccId();
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->isEnableGroup($vccId);
        $agent = $this->get('doctrine.dbal.default_connection')->fetchAssoc(
            "SELECT id,ag_num,ag_name,ag_nickname,ag_role,user_role,crm_datarole,user_queues,group_id,user_type,ag_type,ag_status 
             FROM win_agent WHERE id = :id AND vcc_id = :vcc_id",
            array('id' => $id, 'vcc_id' => $vccId)
        );
        $agent['user_queues'] = !empty($agent['user_queues']) ? explode(",", $agent['user_queues']) : array();
        if ($agent['user_type'] == 3) {
            $agent['user_groups'] = $agent['user_queues'];
        }
        //查询出ag_qu(所属技能组);
        $queues = $this->getDoctrine()->getRepository("IcsocSecurityBundle:WinAgqu")->getQueId($id);
        $que = array();
        if (!empty($queues)) {
            foreach ($queues as $val) {
                $que[] = $val['queId'];
            }
        }
        $agent['belong_queues'] = $que;
        $agent['agent_id'] = $id;
        $agentForm = $this->createForm('agent_info_form', $agent);
        if ($request->getMethod() == 'POST') {
            $arr = $request->get('agent_info_form');
            $arr['belong_queues'] = empty($arr['belong_queues']) ?  array() : $arr['belong_queues'];
            $userType = isset($arr['user_type']) ? $arr['user_type'] : '';
            if ($userType == 3) {
                $arr['user_queues'] = isset($arr['user_groups']) ? $arr['user_groups'] : array();
            }
            $arr['ag_id'] = isset($arr['id']) ? $arr['id'] : 0;
            $arr['vcc_code'] = $user->getVccCode();
            //修改密码
            if (!empty($arr['ag_password']['first']) && $arr['ag_password']['first'] == $arr['ag_password']['second']) {
                /** @var \Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface $encoder */
                $encoder = $this->get('security.encoder_factory')->getEncoder($user);
                $arr['ag_password'] = $encoder->encodePassword($arr['ag_password']['first'], $user->getSalt());
            } else {
                $arr['ag_password'] = "";
            }
            $msg = $this->get('icsoc_data.model.agent')->editAgent($arr);
            if (isset($msg['code']) && ($msg['code'] == 200)) {
                $type = "success";
                $message = $this->trans('Modify the seat of success');
            } else {
                $type = "danger";
                $message = $this->trans('Modify the agents fail').' '.isset($msg['message']) ? $msg['message'] : '';
            }
            $data = array(
                'data' => array(
                    'msg_detail' => $message,
                    'type' => $type,
                    'link' => array(
                        array('text' => $this->trans('return'), 'href' => "javascript:window.history.go(-1)"),
                        array('text' => $this->trans('Seating list'), 'href' => $this->generateUrl('icsoc_agent_index', array('page'=>$page, 'rows'=>$rows, 'filter'=>$filter))),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        return $this->render('IcsocAgentBundle:Agent:agentInfo.html.twig', array(
            'form' => $agentForm->createView(),
            'agentId' => $id,
            'vccId' => $user->getVccId(),
            'userType' => $agent['user_type'],
            'agentType' => $agent['ag_type'],
            'roleGrade' => $roleGrade,
            'isEnableGroup' => $isEnableGroup,
            'page' => $page,
            'rows' => $rows,
            'filter' => $filter,
        ));
    }

    /**
     * 检查坐席工号是否存在；
     *
     * @param Request $request
     *
     * @return Response
     */
    public function checkAction(Request $request)
    {
        $agNum = $request->get('ag_num');
        $agentid = $request->get('agent_id');
        $vccId = $this->getUser()->getVccId();
        //技能组名称重
        $where = " w.vccId = :vccId AND w.agNum = :agNum AND w.isDel = 0 ";
        $param = array('vccId' => $vccId, 'agNum' => $agNum);
        if (!empty($agentid)) {
            $where .= " AND w.id <> :id  ";
            $param['id'] = $agentid;
        }
        $res = $this->getDoctrine()->getRepository("IcsocSecurityBundle:WinAgent")
            ->createQueryBuilder('w')->where($where)->setParameters($param)->getQuery()->getResult();
        if (!empty($res)) {
            return new Response("false");
        }

        return new Response("true");
    }

    /**
     * 普通批量添加；
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function batchAddAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $conn = $this->get("doctrine.dbal.default_connection");
        $vccId = $this->getUser()->getVccId();
        $roleGrade = $this->getRoleGrade();
        if ($request->isMethod('POST')) {
            $vccCode = $this->getUser()->getVccCode();
            $start = $request->get('agent_start', 0);
            $end = $request->get('agent_end', 0);
            $prompt = array(
                'data' => array(
                    'msg_detail' => '',
                    'type' => '',
                    'link' => array(
                        array('text' => $this->trans('return'), 'href' => "javascript:window.history.go(-1)"),
                        array('text' => $this->trans('Seating list'), 'href' => $this->generateUrl('icsoc_agent_index')),
                    ),
                ),
            );
            if (is_numeric($start) && is_numeric($end) && !empty($start) && ($end - $start) > 0) {
                $password = $request->get('agent_password', '');
                $password = !empty($password) && strlen($password) >= 6 ? $password : '123456';
                $encoder = $this->get('security.encoder_factory')->getEncoder($this->getUser());
                $password = $encoder->encodePassword($password, $this->getUser()->getSalt());
                $agentRole = $request->get('agent_role', 0); //坐席角色；
                $belongQue = $request->get('agent_que'); //所属技能组；
                $nickname = $request->get('agent_nickname');//昵称
                //先查询最大坐席数；
                $maxNumber = $em->getRepository("IcsocSecurityBundle:CcCcods")->getMaxAgentNumber($vccId);
                $alreayNumber = $em->getRepository("IcsocSecurityBundle:WinAgent")->getCountAgent($vccId);
                $num = (int) $end - (int) $start + 1;
                if (($num + $alreayNumber) > (int) $maxNumber) {
                    $prompt['data']['type'] = 'danger';
                    $prompt['data']['msg_detail'] = $this->trans('Add fail,Exceed the standard of seats');
                } else {
                    for ($i = $start; $i <= $end; $i++) {
                        $flag = $em->getRepository('IcsocSecurityBundle:WinAgent')->isExsit($i, $vccId);
                        if (!$flag) {
                            /** @var array $roleInfo 角色信息 */
                            $roleInfo = $this->get('icsoc_data.model.role')
                                ->getRoleInfo(array('vcc_code' => $vccCode, 'role_id' => $agentRole));

                            $data = isset($roleInfo['data']) ? $roleInfo['data'] : array();
                            $userType = isset($data['user_type']) ? $data['user_type'] : 0;
                            $userQueues = isset($data['user_queues']) ? $data['user_queues'] : '';

                            $agentData['vcc_id'] = $vccId;
                            $agentData['vcc_code'] = $vccCode;
                            $agentData['ag_num'] = $i;
                            $agentData['ag_name'] = htmlentities($i);
                            $agentData['ag_password'] = $password;
                            $agentData['user_role'] = $agentRole;
                            $agentData['user_type'] = $userType;
                            $agentData['user_queues'] = $userQueues;
                            $agentData['ag_nickname'] = htmlentities($nickname);

                            $conn->insert("win_agent", $agentData);
                            $insertId = $conn->lastInsertId();
                            //写入到队列
                            $agentData['ag_id'] = $insertId;
                            $this->get('icsoc_data.model.agent')->writeMq(array('action' => 'create', 'data' => $agentData));
                            unset($agentData['ag_id']);
                            if (!empty($belongQue)) {
                                $agqu['que_id'] = $belongQue;
                                $agqu['ag_id'] = $insertId;
                                $conn->insert('win_agqu', $agqu);
                            }
                        }
                    }
                    $prompt['data']['type'] = 'success';
                    $prompt['data']['msg_detail'] = $this->trans('Add success');
                }

                return $this->redirect($this->generateUrl('icsoc_ui_message', $prompt));
            }
        }
        $ccRoles = $em->getRepository("IcsocSecurityBundle:CcRoles")
            ->getRolesName(
                "r.vccId = :vccId  AND r.roleGrade > :roleGrade",
                array('vccId' => $vccId, 'roleGrade' => $roleGrade)
            );
        $queues = $em->getRepository("IcsocSecurityBundle:WinQueue")
            ->getQuesName("q.vccId = :vccId AND q.isDel = 0", array('vccId' => $vccId));

        return $this->render("IcsocAgentBundle:Agent:agentBatch.html.twig", array(
            'roles' => $ccRoles,
            'ques' => $queues,
        ));
    }

    /**
     * 导出批量添加模板
     */
    public function exportAction()
    {
        $filed = array(
            'ag_num' => array('name' => $this->trans('Agent number')),
            'ag_name' => array('name' => $this->trans('Username')),
            'ag_pass' => array('name' => $this->trans('Password')),
            'ag_nickname' => array('name' => $this->trans('Agent Nickname')),
        );
        $source = new ArrayType(array(), $filed);
        $this->get('icsoc_core.export.csv')->export($source);
    }

    /**
     * 上传文件；
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function uploadExportAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $roleLevel = $this->getRoleGrade();
        $agentRole = $this->container->get("icsoc_core.common.class")->getFrontAgentRole($roleLevel);// 前台坐席类型
        $dataRole = $this->container->getParameter('select_data_role');
        $vccId = $this->getVccId();
        $userTypes = $this->get("icsoc_core.common.class")->getUserTypes($dataRole, $roleLevel);
        $roles = $em->getRepository("IcsocSecurityBundle:CcRoles")
            ->getRolesName(
                "r.vccId = :vccId AND r.roleGrade > :roleGrade",
                array('vccId' => $vccId, 'roleGrade' => $roleLevel)
            );
        /* 取得所有技能组 */
        $ques = $em->getRepository('IcsocSecurityBundle:WinQueue')
            ->getQuesName("q.vccId = :vccId AND q.isDel = 0", array('vccId' => $vccId));
        /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
        $file = $request->files->get('file_address');
        $valiFile = new File();
        $valiFile->mimeTypes = array('text/comma-separated-values', 'text/plain');
        $valiFile->mimeTypesMessage = $this->trans("The file type is only for %str%", array('%str%' => 'csv,txt'));
        $errorList = $this->container->get("validator")->validateValue($file, $valiFile);
        if (count($errorList) > 0) {
            $data = array(
                'data' => array(
                    'msg_detail' => $this->trans(
                        'Failed to upload file %str%',
                        array('%str%' => $errorList[0]->getMessage())
                    ),
                    'type' => 'danger',
                    'link' => array(
                        array('text' => $this->trans('return'), 'href' => "javascript:window.history.go(-1)"),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        $fileName = time().mt_rand().$vccId.'.csv';
        $targetPath = self::BATCH_DIR.'/'.$fileName;
        $stream = fopen($file->getPathname(), 'r');
        $alioss = $this->container->get("icsoc_filesystem")->putStream($targetPath, $stream);
        if (!$alioss) {
            $data = array(
                'data' => array(
                    'msg_detail' => $this->trans('Failed to upload file %str%', array('%str%' => '写入到flsystem失败')),
                    'type' => 'danger',
                    'link' => array(
                        array('text' => $this->trans('return'), 'href' => "javascript:window.history.go(-1)"),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        return $this->render("IcsocAgentBundle:Agent:export.html.twig", array(
            'roles' => $roles,
            'queues' => $ques,
            'agent_role' => $agentRole,
            'datagrid_name' => $file->getClientOriginalName(),
            'file' => $fileName,
            'data_role' => $userTypes,
        ));
    }

    /**
     * 读取导入的数据；
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function exportDataAction(Request $request)
    {
        $file = $request->get('file', '');
        //$page = $request->get('page', 1);
        // $rows = $request->get('rows', 10);
        $em = $this->getDoctrine()->getManager();
        $agAccount = $em->getRepository("IcsocSecurityBundle:WinAgent")->getAllAgent($this->getVccId());
        $flySys = $this->container->get("icsoc_filesystem");
        //var_dump($flySys);
        $fileName = self::BATCH_DIR.'/'.$file;
        try {
            $stream = $flySys->readStream($fileName);
            $source = $this->get('icsoc_core.export.csv')->readcsv($stream);
            unset($source[0]);
            $data = array();
            foreach ($source as $k => $v) {
                if (count($v) > 4) {
                    return new JsonResponse(array());
                }
                $val = array();
                $val[0] = empty($v[0]) ? '' : $this->get('icsoc_core.export.csv')->convertCharset($v[0], 'GBK', 'UTF-8');
                $val[1] = empty($v[1]) ? '' : $this->get('icsoc_core.export.csv')->convertCharset($v[1], 'GBK', 'UTF-8');
                $val[2] = empty($v[2]) ? '123456' : $this->get('icsoc_core.export.csv')->convertCharset($v[2], 'GBK', 'UTF-8');
                $val[3] = empty($v[3]) ? '' : $this->get('icsoc_core.export.csv')->convertCharset($v[3], 'GBK', 'UTF-8');
                $data[$k] = $val;
            }

            $allCount = count($data);
            $validCount = 0;
            $batch = array();
            $flagArray = array();
            foreach ($data as $key => $val) {
                foreach ($val as $k => $v) {
                    if ($k == 0) {
                        if ($v != '') {
                            if (in_array($v, $agAccount, true) || in_array($v, $flagArray, true)) {
                                break;
                            } else {
                                $patten = " /^[0-9a-zA-Z]+$/";//工号只能是字母数字
                                $flag = preg_match($patten, $v);
                                if ($flag) {
                                    $batch[$key]['ag_num'] = $v;
                                    $flagArray[] = $v;
                                    $validCount++;
                                } else {
                                    break;
                                }
                            }
                        } else {
                            break;
                        }
                    } elseif ($k == 1) {
                        $batch[$key]['ag_name'] = htmlentities($v);
                    } elseif ($k == 2) {
                        $v = $this->get('icsoc_core.common.class')->sbc2Dbc($v);//全角转半角
                        $patten = "/^[^\x{4e00}-\x{9fa5}]{6,}$/u";//密码至少6位且不能为汉字
                        $flag = preg_match($patten, $v);
                        if ($flag) {
                            $batch[$key]['password'] = $v;
                        } else {
                            $batch[$key]['password'] = "123456";
                        }
                    } else {
                        if ($v != '') {
                            $batch[$key]['ag_nickname'] = htmlentities($v);
                        } else {
                            $batch[$key]['ag_nickname'] = htmlentities($val[1]);
                        }
                    }
                }
            }
            $batch = array_filter($batch); //去掉null,false
            sort($batch);
            /*$totalPage = ceil($all_count/$rows);
            $page = $page < 1 ? 1 : $page;
            $page = $page > $totalPage ? $totalPage : $page;
            $offset = ($page - 1) * $rows;
            $arr = array();
            for ($i = $offset; $i <= $offset + $rows; $i++) {
                if (isset($batch[$i])) {
                    $arr[] = $batch[$i];
                }
            }*/
            $datas['rows'] = $batch;
            $datas['records'] = $allCount;
            //$datas['total'] = $totalPage;
            //$datas['page'] = $page;
            $datas['message'] = $this->trans(
                'A total of %total% data, %filter% data filtering',
                array('%total%' => $allCount, '%filter%' => $allCount - $validCount)
            );
            //$flySys->delete($fileName); //删除文件；

            return new JsonResponse($datas);
        } catch (\Exception $e) {
            $this->get('logger')->error($e->getMessage());

            return new JsonResponse(array());
        }
    }

    /**
     * 批量插入数据库
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function batchInsertAction(Request $request)
    {
        $file = $request->get('file', '');
        $fileName = self::BATCH_DIR.'/'.$file;
        $flySys = $this->container->get("icsoc_filesystem");
        $em = $this->getDoctrine()->getManager();
        $validAccount = $request->get('valid_account', '');
        $accountInfo = array();
        $accountArray = array();
        if ($validAccount) {
            $accountInfo = explode("#", $validAccount);
        }
        $accountInfo = array_filter($accountInfo);
        sort($accountInfo);
        foreach ($accountInfo as $v) {
            $accountArray[] = explode(",", $v);
        }
        $params['valid_account'] = $accountArray;
        //$params['vcc_id'] = $this->getVccId();
        $params['vcc_code'] = $this->getVccCode();
        $params['ag_type'] = 1;
        $params['ag_role'] = $request->get('ag_role', '');
        $params['user_role'] = $request->get('user_role', '');
        $params['user_type'] = $request->get('user_type', '');
        $maxAgent = $em->getRepository("IcsocSecurityBundle:CcCcods")->getMaxAgentNumber($this->getVccId());
        $agentCount = $em->getRepository("IcsocSecurityBundle:WinAgent")->getCountAgent($this->getVccId());
        $allowAddNum = ($maxAgent - $agentCount) > 0 ? ($maxAgent - $agentCount) : 0;//获取还能添加的坐席数量
        $params['account_limit'] = $allowAddNum;
        $params['user_queues'] = $request->get('user_queues', '');
        if (!empty($params['valid_account'])) {
            foreach ($params['valid_account'] as $k => $v) {
                $keyRename['ag_num'] = $v[0];
                $keyRename['ag_name'] = $v[1];
                $keyRename['ag_password'] = $v[2];
                $keyRename['ag_nickname'] = $v[3];
                $params['valid_account'][$k] = $keyRename;
            }
        }
        $res = $this->get('icsoc_data.model.agent')->batchAddAgent($params);
        if (isset($res['code']) && $res['code'] == '200') {
            $message = $this->trans('Add success');
            $type = "success";
        } else {
            $message = isset($res['message']) ? $res['message'] : $this->trans('Failed to add');
            $type = "danger";
        }
        $data = array(
            'data' => array(
                'msg_detail' => $message,
                'type' => $type,
                'link' => array(
                    array('text' => $this->trans('Continue to add'), 'href' => $this->generateUrl('icsoc_agent_batch')),
                    array('text' => $this->trans('Seating list'), 'href' => $this->generateUrl('icsoc_agent_index')),
                ),
            ),
        );
        $flySys->delete($fileName); //删除文件；

        return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
    }

    /**
     * 批量修改
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function batchUpdateAction(Request $request)
    {
        $conditions = $request->get('conditions', '');
        $vccCode = $this->getVccCode();
        $arr = json_decode($conditions, true);
        $param = array();
        $update = '';

        if ((!isset($arr['ids']) || empty($arr['ids'])) && (!isset($arr['isall']) || $arr['isall'] != 1)) {
            return new JsonResponse(array('error' => 1, 'message' => $this->trans('Missing parameter')));
        }
        if (isset($arr['username']) && !empty($arr['username'])) {
            $param['ag_name'] = $arr['username'];
            $update .= ",w.agName = :ag_name";
        }
        if (isset($arr['nickname']) && !empty($arr['nickname'])) {
            $param['ag_nickname'] = $arr['nickname'];
            $update .= ",w.agNickname = :ag_nickname";
        }
        if (isset($arr['user_role']) && !empty($arr['user_role'])) {
            $param['user_role'] = $arr['user_role'];
            $update .= ",w.userRole = :user_role";

            /** @var array $roleInfo 角色信息 */
            $roleInfo = $this->container->get('icsoc_data.model.role')
                ->getRoleInfo(array('vcc_code' => $vccCode, 'role_id' => $arr['user_role']));
            $userType = isset($roleInfo['data']['user_type']) ? $roleInfo['data']['user_type'] : 0;
            $userQueues = isset($roleInfo['data']['user_queues']) ? $roleInfo['data']['user_queues'] : '';

            $param['user_type'] = $userType;
            $update .= ",w.userType = :user_type";

            $param['user_queues'] = $userQueues;
            $update .= ",w.userQueues = :user_queues";
        }

        //不限是0
        if (isset($arr['user_type']) && $arr['user_type'] !== false) {
            $param['user_type'] = $arr['user_type'];
            $update .= ",w.userType = :user_type";
        }
        //非坐席是0
        if (isset($arr['ag_role']) && $arr['ag_role'] !== false) {
            $param['ag_role'] = $arr['ag_role'];
            $update .= ",w.agRole = :ag_role";
        }
        if (isset($arr['user_group']) && !empty($arr['user_group'])) {
            $param['user_group'] = $arr['user_group'];
            $update .= ",w.groupId = :user_group";
        }
        if (isset($arr['ag_status']) && !empty($arr['ag_status'])) {
            $param['ag_status'] = $arr['ag_status'];
            $update .= ",w.agStatus = :ag_status";
        }
        if (empty($param) && empty($arr['belong_ques'])) {
            return new JsonResponse(array('error' => 1, 'message' => $this->trans('Missing parameter')));
        }
        $em = $this->getDoctrine()->getManager();
        $ids = "0";
        if (isset($arr['isall']) && $arr['isall'] == 1) {
            //全选；
            $info = array();
            $filter = !empty($arr['filter']) ? json_decode($arr['filter'], true) : array();
            $isCancel = $arr['iscancel'];
            if (!empty($isCancel)) {
                $cancel = array_unique($isCancel);
                $filter['notid'] = implode(',', $cancel);
            }
            $info['filter'] = $filter;
            //获取坐席id;
            $data = $this->get('icsoc_data.model.agent')->listAgent(array('vcc_code' => $vccCode, 'info' => json_encode($info)));
            $data = isset($data['data']) ? $data['data'] : array();
            $ids = array(0);
            foreach ($data as $val) {
                $ids[] = $arr['ids'][] = $val['ag_id'];
            }
            $ids = implode(",", $ids);
        } elseif (isset($arr['isall']) && $arr['isall'] == 0 && !empty($arr['ids'])) {
            $ids = implode(",", $arr['ids']);
        }
        if (!empty($param)) {
            $update = substr($update, 1, strlen($update));
            $em->createQuery(
                "UPDATE IcsocSecurityBundle:WinAgent w SET {$update}
                WHERE w.id IN ($ids)"
            )->setParameters($param)->execute();
            if (isset($param['user_group'])) {
                $user = $this->getUser();
                $flag = $user->getFlag();
                if ($flag != 'ccadmin') {
                    $userNum = $flag == 'ccod' ? '管理员:' : '用户:';
                    $username = $flag == 'ccod' ? $user->getAdminName() : $user->getAgName();
                } else {
                    $userNum = 'ccAdmin';
                    $username = $user->getAccount();
                }
                $this->container->get('icsoc.manage.logger')->info(
                    sprintf(
                        "用户【%s:%s:%s】将企业【%s】下的坐席【%s】分配到业务组【%s】",
                        $userNum,
                        $username,
                        $request->getClientIp(),
                        $vccCode,
                        $ids,
                        $param['user_group']
                    )
                );
            }
            //写入队列
            $idsArray = explode(',', $ids);
            foreach ($idsArray as $agId) {
                $param['vcc_id'] = $this->getVccId();
                $param['ag_id'] = $agId;
                $this->get('icsoc_data.model.agent')->writeMq(array('action' => 'update', 'data' => $param));
            }
        }

        if (isset($arr['belong_ques']) && !empty($arr['belong_ques'])) {
            /** @var \Icsoc\SecurityBundle\Entity\WinAgquRepository $agQu 所属技能组 */
            $agQu = $em->getRepository("IcsocSecurityBundle:WinAgqu");
            $address = $this->container->get('icsoc_core.common.class')->newGetWinIp();
            $port = $this->container->getParameter('win_socket_port');
            foreach ($arr['ids'] as $id) {
                /*
                $agqu = $em->getRepository("IcsocSecurityBundle:WinAgqu")
                     ->findBy(array('queId'=>$arr['belong_ques'],'agId'=>$id));
                if (!$agqu) {
                    $agquObj = new WinAgQu();
                    $agquObj->setAgId($id);
                    $agquObj->setQueId($arr['belong_ques']);
                    $em->persist($agquObj);
                    $em->flush();
                }*/
                $agQu->deleteAgQu($id);
                $agquObj = new WinAgqu();
                $agquObj->setAgId($id);
                $agquObj->setQueId($arr['belong_ques']);
                $em->persist($agquObj);
                $em->flush();
                $this->container->get('icsoc_data.validator')->reloadAgent($this->getVccId(), $address, $id, $port);
            }
        }

        return new JsonResponse(array('error' => 0, 'message' => $this->trans('Update success')));
    }

    /**
     * 坐席签入；
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function loginAction(Request $request)
    {
        $phone = $request->get("phone");
        $agNum = $request->get("ag_num");
        $vccCode = $this->getVccCode();
        $params = array('vcc_code' => $vccCode, 'data' => array(array('ag_num' => $agNum, 'phone' => $phone)));
        $result = $this->get("icsoc_data.model.agent")->staticAgentLogin($params);
        if (isset($result['code']) && $result['code'] == 200) {
            return new JsonResponse(array('error' => 0));
        } else {
            /*
            $errors = isset($result['errors']) ? $result['errors'] : array();
            $smsg = $emsg = '';
            foreach ($errors as $error) {
                if ($error['code'] == 200) {
                    $smsg.= $error['data'].',';
                } else {
                    $emsg.= $error['data'].',';
                }
            }
            $message = $this->trans('success').'['.$smsg.']'.$this->trans('fail').'['.$emsg.']';*/
            return new JsonResponse(
                array(
                    'error' => 1,
                    'message' => $this->trans('fail').'['.$result['errors'][0]['message'].']',
                )
            );
        }
    }

    /**
     * 签出
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function logoutAction(Request $request)
    {
        $agNum = $request->get("ag_num");
        $vccCode = $this->getVccCode();
        $params = array('vcc_code' => $vccCode, 'data' => array(array('ag_num' => $agNum)));
        $vccId = $this->getVccId();
        $agId = $this->get('doctrine.dbal.default_connection')
            ->fetchColumn("SELECT id FROM win_agent WHERE vcc_id = ? AND ag_num = ? AND is_del = 0", array($vccId, $agNum));
        $key = sprintf("vcc_id:%s:ag_id:%s", $vccId, $agId);
        //先判断是否是通话状态
        $this->get('snc_redis.default')->select('3');
        $this->get('snc_redis.default')->getOptions()->profile->getProcessor()->setPrefix('');
        $agStatus = $this->get('snc_redis.default')->hget($key, 'ag_status');
        if (in_array($agStatus, array(41, 42))) {
            return new JsonResponse(array('error'=>1, 'message'=>'该坐席通话中不能修改'));
        }
        $result = $this->get("icsoc_data.model.agent")->staticAgentLogout($params);
        if (isset($result['code']) && $result['code'] == 200) {
            return new JsonResponse(array('error' => 0));
        } else {
            /*
            $errors = isset($result['errors']) ? $result['errors'] : array();
            $smsg = $emsg = '';
            foreach ($errors as $error) {
                if ($error['code'] == 200) {
                    $smsg.= $error['data'].',';
                } else {
                    $emsg.= $error['data'].',';
                }
            }
            $message = $this->trans('success').'['.$smsg.']'.$this->trans('fail').'['.$emsg.']';*/
            return new JsonResponse(
                array(
                    'error' => 1,
                    'message' => $this->trans('fail').'['.$result['errors'][0]['message'].']',
                )
            );
        }
    }

    /**
     * 修改分机 = 签出 + 签入
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function editPhoneAction(Request $request)
    {
        $phone = $request->get("phone");
        $agNum = $request->get("ag_num");
        $vccCode = $this->getVccCode();
        $vccId = $this->getVccId();
        $agId = $this->get('doctrine.dbal.default_connection')
            ->fetchColumn("SELECT id FROM win_agent WHERE vcc_id = ? AND ag_num = ? AND is_del=0", array($vccId, $agNum));
        $key = sprintf("vcc_id:%s:ag_id:%s", $vccId, $agId);
        //先判断是否是通话状态
        $this->get('snc_redis.default')->select('3');
        $this->get('snc_redis.default')->getOptions()->profile->getProcessor()->setPrefix('');
        $agStatus = $this->get('snc_redis.default')->hget($key, 'ag_status');
        if (in_array($agStatus, array(41, 42))) {
            return new JsonResponse(array('error'=>1, 'message'=>'该坐席通话中不能修改'));
        }
        //先签出
        $outData = array('vcc_code' => $vccCode, 'data' => array(array('ag_num' => $agNum)));
        $result = $this->get("icsoc_data.model.agent")->staticAgentLogout($outData);
        if (!isset($result['code']) || $result['code'] != 200) {
            return new JsonResponse(
                array(
                    'error' => 1,
                    'message' => $this->trans('fail').'['.$result['errors'][0]['message'].']',
                )
            );
        }
        $loginData = array('vcc_code' => $vccCode, 'data' => array(array('ag_num' => $agNum, 'phone' => $phone)));
        $result = $this->get("icsoc_data.model.agent")->staticAgentLogin($loginData);
        if (isset($result['code']) && $result['code'] == 200) {
            return new JsonResponse(array('error' => 0));
        } else {
            return new JsonResponse(
                array(
                    'error' => 1,
                    'message' => $this->trans('fail').'['.$result['errors'][0]['message'].']',
                )
            );
        }
    }

    /**
     * 刷新静态坐席 签出+签入
     * @return JsonResponse
     */
    public function resetAllAction()
    {
        $vccId = $this->getVccId();
        $date = $this->get('icsoc_data.model.agent')->getReadyAgent(array('vcc_id'=>$vccId));

        return new JsonResponse($date);
    }

    /**
     * 检查坐席数量；
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function checkNumAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $account = $request->get('account', '');
        $accountInfo = array();
        $accountArray = array();
        if ($account) {
            $accountInfo = explode("#", $account);
        }
        $accountInfo = array_filter($accountInfo);
        sort($accountInfo);
        foreach ($accountInfo as $v) {
            $accountArray[] = explode(",", $v);
        }
        $res = $em->getRepository("IcsocSecurityBundle:WinAgent")->getAllAgent($this->getVccId());
        $hasHaddle = array();
        foreach ($res as $v) {
            foreach ($accountArray as $key => $val) {
                if ($val[0] == $v) {
                    $hasHaddle[] = $v;
                    unset($accountArray[$key]);
                }
            }
        }
        $maxAgent = $em->getRepository("IcsocSecurityBundle:CcCcods")->getMaxAgentNumber($this->getVccId());
        $agentCount = $em->getRepository("IcsocSecurityBundle:WinAgent")->getCountAgent($this->getVccId());
        $allowAddNum = ($maxAgent - $agentCount) > 0 ? ($maxAgent - $agentCount) : 0;//获取还能添加的坐席数量
        $message = $this->trans(
            'Seat number you want to add to the %count% can continue to add seats for %allow%, whether to continue to add?',
            array('%allow%' => $allowAddNum, '%count%' => count($accountArray))
        );

        return new JsonResponse(array('num' => $allowAddNum, 'rows' => $hasHaddle, 'message' => $message));
    }

    /**
     * 检查坐席数量是否超标；
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function checkAgentAllowNumAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $num = (int) $request->get("num", '');
        $vccId = $this->getVccId();
        //先查询最大坐席数；
        $maxNumber = (int) $em->getRepository("IcsocSecurityBundle:CcCcods")->getMaxAgentNumber($vccId);
        $alreayNumber = (int) $em->getRepository("IcsocSecurityBundle:WinAgent")->getCountAgent($vccId);
        if ($alreayNumber + $num > $maxNumber) {
            return new JsonResponse(array('error' => true, 'num' => ($maxNumber - $alreayNumber)));
        }

        return new JsonResponse(array('error' => false));

    }

    /**
     * 导出
     *
     * @param Request $request
     *
     * @return mixed|void
     */
    public function exportAgentAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $filter = $request->get("filter", '');
        $sord = $request->get('sord', 'DESC');
        $sidx = $request->get('sidx', '');
        $isAll = $request->get("isall", '');
        $ids = $request->get("ids", '');
        $vccId = $this->getVccId();
        $filter = !empty($filter) ? json_decode($filter, true) : array();
        $info = array(
            'pagination' => array('rows' => 100000, 'page' => 1),
            'sort' => array('order' => $sord, 'field' => empty($sidx) ? 'id' : $sidx),
        );
        if ($isAll == 1) {
            //全选；
            $isCancel = $request->get("iscancelIds");
            if (!empty($isCancel)) {
                $cancel = explode(",", $isCancel);
                $cancel = array_unique($cancel);
                $filter['notid'] = implode(',', $cancel);
            }
            $condtions = $this->get("icsoc_core.common.class")->getUserTypeCondition();
            if (isset($condtions['user_role']) && !empty($condtions['user_role'])) {
                $filter['user_role'] = implode(',', $condtions['user_role']);
            }
            if (isset($condtions['ag_id']) && !empty($condtions['ag_id'])) {
                $filter['id'] = implode(',', $condtions['ag_id']);
            }
        } elseif ($isAll == 0 && !empty($ids)) {
            $filter['id'] = $ids;
        }
        $info['filter'] = $filter;
        $vccCode = $this->getUser()->getVccCode();
        $list = $this->get('icsoc_data.model.agent')->listAgent(
            array(
                'vcc_code' => $vccCode,
                'info' => json_encode($info),
            )
        );
        if (isset($list) && !empty($list)) {
            $agentRole = $this->container->getParameter("front_agent_type"); //坐席角色
            $selectDataRole = $this->container->getParameter("select_data_role"); //坐席角色
            /*获取所有业务组*/
            $groups = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
            //获取所有技能组
            $queues = $em->getRepository('IcsocSecurityBundle:WinQueue')
                ->getQuesName("q.vccId = :vccId AND q.isDel = 0", array('vccId' => $vccId));
            foreach ($list['data'] as $k => $v) {
                $v['id'] = $v['ag_id'];
                $v['ag_name'] = isset($v['ag_name']) ? $v['ag_name'] : '';
                $v['group_name'] = isset($groups[$v['group_id']]) ? $groups[$v['group_id']] : '';
                $v['ag_role'] = isset($agentRole[$v['ag_role']]) ? $agentRole[$v['ag_role']] : '';
                $v['user_type'] = isset($selectDataRole[$v['user_type']]) ? $selectDataRole[$v['user_type']] : '';
                $v['crm_datarole'] = isset($selectDataRole[$v['crm_datarole']]) ?
                    $selectDataRole[$v['crm_datarole']] : '';
                $queIds = $em->getRepository('IcsocSecurityBundle:WinAgqu')
                    ->getQueId($v['ag_id']);
                $userQueues = '';
                $ellipsis = '';
                foreach ($queIds as $key => $value) {
                    $ellipsis .= isset($queues[$value['queId']]) ? $queues[$value['queId']].',' : '';
                    $userQueues .= isset($queues[$value['queId']]) ? $queues[$value['queId']].',' : '';
                }
                $v['queues'] = !empty($ellipsis) ? substr($ellipsis, 0, -1) : $this->trans('Unallocated');
                /*if (count($queIds) > 2) {
                    $v['queues'] .= '...';
                }*/
                $list['data'][$k] = $v;
            }
        }
        $data = isset($list['data']) ? $list['data'] : array();
        foreach ($data as $key => $val) {
            if ($val['ag_type'] != 2) {
                $data[$key]['pho_num'] = '';
            }
        }
        //查看业务组权限
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->isEnableGroup($vccId);
        $title = array(
            'ag_num' => array(
                'title' => $this->trans('Agent number'),
                'type' => Col::TYPE_STRING,
            ),
            'ag_name' => array(
                'title' => $this->trans('Username'),
                'type' => Col::TYPE_STRING,
            ),
            'ag_nickname' => array(
                'title' => $this->trans('Nickname'),
                'type' => Col::TYPE_STRING,
            ),
            'role_name' => array(
                'title' => $this->trans('User role'),
                'type' => Col::TYPE_STRING,
            ),
            'queues' => array(
                'title' => $this->trans('Belongs to the skill set'),
                'type' => Col::TYPE_STRING,
            ),
            'user_type' => array(
                'title' => $this->trans('Data access'),
                'type' => Col::TYPE_STRING,
            ),
            'ag_role' => array(
                'title' => $this->trans('Seat type'),
                'type' => Col::TYPE_STRING,
            ),
            'crm_datarole' => array(
                'title' => $this->trans('CRM permissions'),
                'type' => Col::TYPE_STRING,
            ),
            'ag_status' => array(
                'title' => '坐席状态',
                'type' => Col::TYPE_STRING,
            ),
        );
        if ($isEnableGroup) {
            $title = array(
                'ag_num' => array(
                    'title' => $this->trans('Agent number'),
                    'type' => Col::TYPE_STRING,
                    ),
                'ag_name' => array(
                    'title' => $this->trans('Username'),
                    'type' => Col::TYPE_STRING,
                    ),
                'ag_nickname' => array(
                    'title' => $this->trans('Nickname'),
                    'type' => Col::TYPE_STRING,
                    ),
                'role_name' => array(
                    'title' => $this->trans('User role'),
                    'type' => Col::TYPE_STRING,
                    ),
                'queues' => array(
                    'title' => $this->trans('Belongs to the skill set'),
                    'type' => Col::TYPE_STRING,
                    ),
                'group_name' => array(
                    'title' => $this->trans('The business group'),
                    'type' => Col::TYPE_STRING,
                    ),
                'user_type' => array(
                    'title' => $this->trans('Data access'),
                    'type' => Col::TYPE_STRING,
                    ),
                'ag_role' => array(
                    'title' => $this->trans('Seat type'),
                    'type' => Col::TYPE_STRING,
                    ),
                'crm_datarole' => array(
                    'title' => $this->trans('CRM permissions'),
                    'type' => Col::TYPE_STRING,
                    ),
                'ag_status' => array(
                    'title' => '坐席状态',
                    'type' => Col::TYPE_STRING,
                ),
            );
        }
        //需要权限控制显示的字段
        $actionList = $this->getActionList();
        $actions = explode(',', $actionList);
        $isLogin = ($actionList == 'all' || in_array('icsoc_agent_login', $actions)) ? true : false;
        $loginEnter = ($actionList == 'all' || in_array('icsoc_agent_login_enter', $actions)) ? true : false;
        $loginEdit = ($actionList == 'all' || in_array('icsoc_agent_login_edit', $actions)) ? true : false;
        if ($isLogin || $loginEnter || $loginEdit) {
            $title['pho_num'] = array(
                'title' => '登录状态',
                'type' => Col::TYPE_STRING,
            );
        }

        return $this->container->get('icsoc_data.model.batchExport')->exportExcel($title, $data);
        //return $this->get('icsoc_core.export.excel')->export($excel);
    }
}
